<template>
  <div class="page-container-padding">
    <div>
      <el-select v-model="curVarietyCode" filterable size="mini">
        <el-option
          v-for="v in varietyList"
          :key="v.code"
          :value="v.code"
          :label="`${v.name} (${v.code})`"
        />
      </el-select>
      <el-button
        type="primary"
        size="mini"
        style="margin-left: 6px"
        :loading="queryLoading"
        @click="toQueryIndexGroup"
      >
        查询
      </el-button>
    </div>
    <div class="new-group">
      <div>父级：</div>
      <div class="parent-group">{{ curGroupName }}</div>
      <el-input
        v-model="curNewGroupName"
        placeholder="新建分组，无选择父级时为顶级分组(双击表行选择)"
        style="margin-left: 6px; width: 350px"
        size="mini"
      ></el-input>
      <el-button
        size="mini"
        type="primary"
        style="margin-left: 6px"
        :loading="createNewGroupLoading"
        @click="toCreateNewGroup"
      >
        确定新建
      </el-button>
    </div>
    <div class="header-name">分组列表：</div>
    <div>
      <el-table
        border
        stripe
        lazy
        highlight-current-row
        row-key="id"
        :load="loadChildren"
        :data="groupList"
        @row-dblclick="handleCurrentRow"
      >
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="sort_num" label="排序" width="70" />
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_active ? 'success' : 'danger'"
            >
              {{ scope.row.is_active ? '公开' : '隐蔽' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" align="center">
          <template #default="scope">
            <el-button type="text" @click="toUpdateGroup(scope.row)">
              编辑
            </el-button>
            <el-button
              type="text"
              style="color: #d2291e"
              @click="toDeleteGroup(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="header-name">
      <span style="color: #d2291e">{{ curGroupName }}&nbsp;</span>
      <span>指标列表：</span>
      <span>
        <el-button size="mini" type="text" @click="toCreateNewIndex">
          新增指标
        </el-button>
      </span>
      <span style="margin-left: auto">
        <el-button
          size="mini"
          type="text"
          style="color: #d2291e"
          @click="toClearGoupIndexes"
        >
          清空指标
        </el-button>
      </span>
    </div>
    <div>
      <el-table border stripe :data="groupIndexList">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="alone" label="配置1" width="150" />
        <el-table-column prop="formula" label="配置2" width="250" />
        <el-table-column prop="stack" label="配置3" width="250" />
        <el-table-column
          prop="unit"
          label="单位"
          width="70"
          show-overflow-tooltip
        />
        <el-table-column prop="sort_num" label="排序" width="70" />
        <el-table-column label="主要" width="60" align="center">
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_primary ? 'success' : 'danger'"
            >
              {{ scope.row.is_primary ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="110" align="center">
          <template #default="scope">
            <el-tag
              size="mini"
              :type="scope.row.is_active ? 'success' : 'danger'"
            >
              {{ scope.row.is_active ? '公开' : '隐蔽' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="90" align="center">
          <template #default="scope">
            <el-button type="text" @click="toUpdateGroupIndex(scope.row)">
              编辑
            </el-button>
            <el-button
              type="text"
              style="color: #d2291e"
              @click="toDeleteGroupIndex(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="line-height: 23px">
      <div>配置说明:</div>
      <div>配置1: 长度为2的元组(指标id,图形类型)</div>
      <div>配置2: 长度为2的元组(公式,图形类型)，其中公式中：字符i+指标id</div>
      <div>配置3: 长度为2的列表[(轴位置,指标id,图形类型)]</div>
      <div>先配先用原则。</div>
    </div>
    <!-- 编辑组弹窗 -->
    <el-dialog :visible.sync="editRow.showEdit" title="修改分组">
      <el-form size="mini" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editRow.name" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editRow.is_active"
            active-text="公开"
            inactive-text="隐蔽"
          />
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="editRow.sort_num"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editRow.showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editRow.saveLoading"
          @click="toSaveUpdateRow"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑组内指标弹窗 -->
    <el-dialog :visible.sync="editGroupIndexRow.showEdit" title="修改组内指标">
      <el-form size="mini" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="editGroupIndexRow.name"></el-input>
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="editGroupIndexRow.unit"></el-input>
        </el-form-item>
        <el-form-item label="配置1">
          <el-input v-model="editGroupIndexRow.alone"></el-input>
        </el-form-item>
        <el-form-item label="配置2">
          <el-input v-model="editGroupIndexRow.formula"></el-input>
        </el-form-item>
        <el-form-item label="配置3">
          <el-input v-model="editGroupIndexRow.stack"></el-input>
        </el-form-item>
        <el-form-item label="序号">
          <el-input v-model="editGroupIndexRow.sort_num"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editGroupIndexRow.is_active"
            active-text="公开"
            inactive-text="隐蔽"
          />
        </el-form-item>
        <el-form-item label="主要">
          <el-switch
            v-model="editGroupIndexRow.is_primary"
            active-text="是"
            inactive-text="否"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="editGroupIndexRow.showEdit = false">取消</el-button>
        <el-button
          type="primary"
          :loading="editGroupIndexRow.saveLoading"
          @click="toSaveGroupIndexRow"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
    <!-- 新建组内指标弹窗 -->
    <el-dialog :visible.sync="newIndex.isShow" title="组内新建指标">
      <div style="padding: 8px 10px">
        <el-form size="mini" label-width="80px">
          <el-form-item label="搜索">
            <div class="select-index">
              <el-select
                v-model="indexSelected"
                filterable
                remote
                :remote-method="queryIndexesList"
              >
                <el-option
                  v-for="i in indexSelectList"
                  :key="i.id"
                  :value="i.id"
                  :label="i.name + `(${i.plat})`"
                ></el-option>
              </el-select>
              <div style="margin-left: 8px">
                <span>ID=</span>
                <span style="color: #d2291e; font-weight: 600">
                  {{ indexSelected }}
                </span>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="新名称">
            <el-input
              v-model="newIndex.name"
              placeholder="新的指标名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="新单位">
            <el-input
              v-model="newIndex.unit"
              placeholder="新的指标单位"
            ></el-input>
          </el-form-item>
          <el-form-item label="配置1">
            <el-input
              v-model="newIndex.alone"
              placeholder="(1,'line')"
            ></el-input>
          </el-form-item>
          <el-form-item label="配置2">
            <el-input
              v-model="newIndex.formula"
              placeholder="('i1+i2','line')"
            ></el-input>
          </el-form-item>
          <el-form-item label="配置3">
            <el-input
              v-model="newIndex.stack"
              placeholder="[(0,1,'line'),(1,2,'bar')]"
            ></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="newIndex.isShow = false">取消</el-button>
        <el-button
          type="primary"
          :loading="newIndex.saveLoading"
          @click="toSaveNewGroupIndex"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { RetrieveVariety } from '@/api/adminRuizhi/common'
  import {
    RetrieveIndex,
    CreateIndexGroup,
    RetrieveIndexGroup,
    DeleteIndexGroup,
    UpdateIndexGroup,
    GroupIndex,
    UpdateGroupIndex,
    CreateGroupIndex,
    ClearGroupIndex,
    DeleteGroupIndexOne,
  } from '@/api/adminRuizhi/dataindexlib'
  export default {
    data() {
      return {
        varietyList: [],
        curVarietyCode: null,
        groupList: [],
        queryLoading: false,
        editRow: {
          showEdit: false,
          gid: null,
          name: '',
          is_active: null,
          sort_num: null,
          saveLoading: false,
        },
        curNewGroupName: '',
        curGroupId: 0,
        curGroupName: '',
        createNewGroupLoading: false,
        groupIndexList: [],
        editGroupIndexRow: {
          showEdit: false,
          rid: -1,
          sort_num: null,
          is_active: false,
          is_primary: false,
          name: '',
          alone: '',
          formula: '',
          stack: '',
          unit: '',
          vcode: '',
          saveLoading: false,
        },
        newIndex: {
          isShow: false,
          name: '',
          alone: '',
          formula: '',
          stack: '',
          unit: '',
          saveLoading: false,
        },
        indexSelected: null,
        indexSelectList: [],
      }
    },
    watch: {
      indexSelected(n) {
        // console.log(n)
        this.newIndex.alone = `(${n},"line")`
        const obj = this.getSelectedIndexObj(n)
        if (obj) {
          this.newIndex.name = obj.name
          this.newIndex.unit = obj.unit
        }
      },
    },
    mounted() {
      // S04为数据库空间品种
      RetrieveVariety(null, 'S04').then((res) => {
        this.varietyList = res.data.data
      })
    },
    methods: {
      // 关键字查询指标
      queryIndexesList(keyword) {
        if (keyword.length < 1) return
        RetrieveIndex(keyword).then((res) => {
          const resData = res.data
          this.indexSelectList = resData.data.rows
        })
      },

      // 查询数据
      toQueryIndexGroup() {
        if (!this.curVarietyCode) {
          this.$baseMessage('请先选择品种再查询!', 'error')
          return
        }
        this.groupList = []
        this.queryLoading = true
        RetrieveIndexGroup(this.curVarietyCode, 0).then((res) => {
          const resData = res.data
          this.groupList = resData.data.map((item) => {
            item.children = []
            item.hasChildren = true
            return item
          })
          this.curGroupId = 0
          this.curGroupName = '无'
          this.queryLoading = false
          this.groupIndexList = []
        })
      },

      // 懒加载子数据
      loadChildren(tree, treeNode, resolve) {
        RetrieveIndexGroup(this.curVarietyCode, tree.id).then((res) => {
          const resData = res.data
          resolve(
            resData.data.map((item) => {
              item.children = []
              item.hasChildren = true
              return item
            })
          )
        })
      },

      // 设置当前组和查询当前组指标
      handleCurrentRow(crow) {
        this.curGroupId = crow.id
        this.curGroupName = crow.name
        this.curGroupId = crow.id
        this.curGroupName = crow.name
        this.getGroupIndex()
      },

      // 查询当前分组下的指标
      getGroupIndex() {
        GroupIndex(this.curGroupId).then((res) => {
          this.groupIndexList = res.data.data
        })
      },

      // 新建分组
      toCreateNewGroup() {
        if (!this.curVarietyCode || this.curNewGroupName.length < 1) {
          this.$baseMessage('请先选择品种并输入名称再添加!', 'error')
          return
        }
        const bodyData = {
          name: this.curNewGroupName,
          vcode: this.curVarietyCode,
          parent_id: this.curGroupId,
        }
        this.createNewGroupLoading = true
        CreateIndexGroup(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.toQueryIndexGroup()
          this.createNewGroupLoading = false
        })
      },

      toUpdateGroup(row) {
        this.editRow.gid = row.id
        this.editRow.name = row.name
        this.editRow.sort_num = row.sort_num
        this.editRow.is_active = row.is_active
        this.editRow.showEdit = true
      },

      toDeleteGroup(row) {
        this.$baseConfirm(
          '将删除分组及其组内指标,操作不可恢复!',
          '警告',
          () => {
            DeleteIndexGroup(row.id).then((res) => {
              this.$baseMessage(res.message, 'success')
              this.toQueryIndexGroup()
            })
          }
        )
      },

      toSaveUpdateRow() {
        const bodyData = {
          gid: this.editRow.gid,
          name: this.editRow.name,
          sort_num: this.editRow.sort_num,
          is_active: this.editRow.is_active ? 1 : 0,
        }
        this.editRow.saveLoading = true
        UpdateIndexGroup(bodyData).then((res) => {
          this.editRow.saveLoading = false
          this.editRow.showEdit = false
          this.$baseMessage(res.message, 'success')
          this.toQueryIndexGroup()
        })
      },

      // 获取弹窗选择指标等待新建的对象
      getSelectedIndexObj(iid) {
        let obj = null
        for (let i = 0; i < this.indexSelectList.length; i++) {
          if (this.indexSelectList[i].id === iid) {
            obj = this.indexSelectList[i]
            break
          }
        }
        return obj
      },

      // 准备编辑组内的指标配置
      toUpdateGroupIndex(row) {
        this.editGroupIndexRow.rid = row.id
        this.editGroupIndexRow.name = row.name
        this.editGroupIndexRow.sort_num = row.sort_num
        this.editGroupIndexRow.alone = row.alone
        this.editGroupIndexRow.formula = row.formula
        this.editGroupIndexRow.stack = row.stack
        this.editGroupIndexRow.unit = row.unit
        this.editGroupIndexRow.is_active = row.is_active
        this.editGroupIndexRow.is_primary = row.is_primary
        this.editGroupIndexRow.vcode = row.vcode
        this.editGroupIndexRow.showEdit = true
      },

      // 保存组内的指标配置
      toSaveGroupIndexRow() {
        const bodyData = { ...this.editGroupIndexRow }
        UpdateGroupIndex(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.editGroupIndexRow.rid = 0
          this.editGroupIndexRow.showEdit = false
          this.getGroupIndex()
        })
      },

      // 准备在组内新建指标
      toCreateNewIndex() {
        if (this.curGroupId < 1 || !this.curVarietyCode) {
          this.$baseMessage('请先选择品种和双击选择组后再新建!')
          return
        }
        this.newIndex.isShow = true
      },
      // 保存组内新建的指标
      toSaveNewGroupIndex() {
        const bodyData = {
          name: this.newIndex.name,
          alone: this.newIndex.alone,
          formula: this.newIndex.formula,
          stack: this.newIndex.stack,
          unit: this.newIndex.unit,
          vcode: this.curVarietyCode,
          gid: this.curGroupId,
        }
        this.newIndex.saveLoading = true
        CreateGroupIndex(bodyData).then((res) => {
          this.$baseMessage(res.message, 'success')
          this.getGroupIndex()
          this.newIndex.isShow = false
          this.newIndex.saveLoading = false
        })
      },

      // 删除组内一个指标
      toDeleteGroupIndex(row) {
        this.$baseConfirm('将删除该指标，操作不可恢复!', '警告', () => {
          DeleteGroupIndexOne(row.id).then((res) => {
            this.$baseMessage(res.message, 'success')
            this.getGroupIndex()
          })
        })
      },

      // 清空组内的指标
      toClearGoupIndexes() {
        this.$baseConfirm('将清空组内的指标，操作不可恢复!', '警告', () => {
          ClearGroupIndex(this.curGroupId).then((res) => {
            this.$baseMessage(res.message, 'success')
            this.getGroupIndex()
          })
        })
      },
    },
  }
</script>
<style scoped lang="scss">
  .new-group {
    display: flex;
    align-items: center;
    margin-top: 8px;
    .parent-group {
      color: #ed2400;
      font-weight: 600;
    }
  }
  .header-name {
    margin: 8px 0;
    color: #349cfc;
    font-weight: 600;
    display: flex;
    align-items: center;
  }
  .select-index {
    display: flex;
    align-items: center;
  }
</style>
